<template>
	<view class="wrap">
		<!-- top start -->
		<!-- @subCurrent if true 外卖 else 堂食-->
		<view v-if="subCurrent == 1">
			<!-- address start-->
			<view class="address" @click="goToAddress()">
				<view>
					<view class="u-font-weight">
						{{address.provinceName+address.cityName+address.districtName+address.detail}}
					</view>
					<view class="u-font-24 u-type-info u-m-t-15">
						<text class="u-m-r-10">{{address.consignee}}</text>
						<text>{{address.phone.substring(0,3)+"****"+address.phone.substring(7)}}</text>
					</view>
				</view>
				<view>
					<u-icon name="arrow-right" color="#909399"></u-icon>
				</view>
			</view>

			<!-- slot -->
			<u-gap height="20" bg-color="#f3f4f6"></u-gap>
		</view>
		<!-- top end -->

		<!-- list start -->
		<view class="u-flex u-row-between u-m-t-30 u-m-b-30 u-m-l-30 u-m-r-30">
			<view class="u-font-24 u-font-weight u-content-color">
				私房菜（万达广场店）
			</view>
			<view>
				<u-tag :text="subCurrent == 1 ? '外卖' : '堂食'" mode="dark" bg-color="#EE2F37" size="mini" />
			</view>
		</view>
		<view v-for="(item,index) in orderList" :key="index" class="u-flex list-box">
			<view>
				<image class="item-menu-image" :src="item.imageUrl" mode="aspectFill"></image>
			</view>
			<view class="item-menu-name">
				<text class="u-font-26">{{item.name}}</text>
				<view class="u-line-2 u-font-20 u-type-info u-m-t-10 u-m-b-10">
					{{item.description}}
				</view>
				<view class="u-flex u-row-between">
					<view class="u-font-weight u-font-24" style="color: #EE2F37;">
						<text class="u-font-20">￥</text>
						{{item.amount / item.number}}
					</view>
					<view class="u-type-info u-font-22">
						x{{item.number}}
					</view>
				</view>
			</view>
		</view>
		<!-- list end -->

		<!-- cell start -->
		<view class="u-cell-box">
			<u-cell-group :border="false">
				<u-cell-item title="用餐人数" :value="form.people ? form.people+'人' : '请选择'" :title-style="titleStyle"
					:value-style="valueStyle" hover-class="none" @click="PopupModal(0)"
					:border-bottom="false"></u-cell-item>
				<u-cell-item title="配送时间" :value="form.mealsTime ? form.mealsTime : '请选择'" :title-style="titleStyle"
					:value-style="valueStyle" hover-class="none" @click="TimerShow = true" :border-bottom="false"
					v-if="subCurrent==1"></u-cell-item>
				<u-cell-item title="留言" :border-bottom="false" :title-style="titleStyle"
					:value="form.leave ? (form.leave.length > 10 ? form.leave.slice(0, 10) + '...' : form.leave) : '无'"
					:value-style="valueStyle" hover-class="none" @click="PopupModal(1)"></u-cell-item>
			</u-cell-group>
		</view>
		<!-- cell end -->

		<!-- slot -->
		<u-gap height="100"></u-gap>

		<!-- button start -->
		<view class="u-bottom">
			<!-- 添加遮罩层 -->
			<view class="mask" v-if="showPriceDetail" @tap.stop="togglePriceDetail"></view>

			<view class="u-bottom__wrap">
				<view class="u-font-weight u-font-40 u-m-l-20">
					<text class="u-font-24">￥</text>
					{{orderPrice.toFixed(2)}}
				</view>
				<view class="u-bottom__nums">
					共 {{orderNum}} 件商品
					<view class="check-detail" @tap="togglePriceDetail">
						<text>查看明细</text>
						<u-icon :name="showPriceDetail ? 'arrow-down' : 'arrow-up'" color="#f37b1d" size="24"></u-icon>
					</view>
				</view>
				<!-- 价格明细折叠面板 -->
				<view class="price-detail-panel" :class="{ 'panel-show': showPriceDetail }" @tap.stop>
					<view class="price-list">
						<view class="price-item" v-for="(item, index) in priceDetails" :key="index">
							<text>{{ item.label }}</text>
							<text :class="{ 'discount': item.isDiscount }">¥{{ item.value.toFixed(2) }}</text>
						</view>
					</view>
				</view>
			</view>
			<view class="u-bottom__place" @click="confirmPay" :class="{'u-bottom__place--disabled': orderPrice <= 0}"
				:style="orderPrice <= 0 ? 'background-color: #c8c9cc;' : ''">
				确认支付
			</view>
		</view>
		<!-- button end -->

		<!-- popup start -->
		<u-popup v-model="PopupShow" mode="bottom" height="80%" border-radius="14" closeable :mask-close-able="false">
			<view v-if="!PopupPage">
				<view class="u-m-l-30 u-m-r-30 u-m-t-30">
					<view>
						<u-image src="/static/menu/index-dining.png" width="220" height="180"></u-image>
					</view>
					<view class="u-font-34 u-font-weight u-m-t-50 u-m-b-50">请选择用餐人数</view>
					<!-- content -->
					<u-grid :col="4" :border="false" hover-class="none">
						<u-grid-item v-for="item in 12" :key="item" :custom-style="customStyle"
							@click="SelectPeople(item)">
							<view class="u-font-weight">
								<!-- #ifdef MP-WEIXIN -->
								{{item+1}}
								<!-- #endif -->
								<!-- #ifdef H5 -->
								{{item}}
								<!-- #endif -->
							</view>
						</u-grid-item>
					</u-grid>
					<u-gap height="30"></u-gap>
				</view>
			</view>
			<!-- leave -->
			<view v-else>
				<view class="u-m-l-30 u-m-r-30 u-m-t-30">
					<view>
						<u-image src="/static/menu/index-leave.jpg" width="220" height="180"></u-image>
					</view>
					<view class="u-font-34 u-font-weight u-m-t-50 u-m-b-50">快捷标签</view>
					<!-- tags -->
					<u-grid :col="4" :border="false" hover-class="none">
						<u-grid-item v-for="item in tags" :key="item" :custom-style="customStyle"
							@click="SelectTags(item)">
							<view class="u-font-weight">{{item}}</view>
						</u-grid-item>
					</u-grid>
					<view class="u-font-34 u-font-weight u-m-t-50 u-m-b-50">自定义留言</view>
					<u-input type="textarea" placeholder="请填写您的需求" placeholder-style="color: #909399"
						:custom-style="inputStyle" v-model="form.leave"></u-input>
					<u-gap height="30"></u-gap>
				</view>
			</view>
		</u-popup>
		<!-- popup end -->

		<!-- timerSelect -->
		<u-picker v-model="TimerShow" mode="time" :params="TimerParams" @confirm="mealsPicker"
			:defaultTime="defaultTime" :start="startTime" :end="endTime">
		</u-picker>

		<!-- 优惠券选择 -->
		<view class="discount-section">
			<view class="section-item" @tap="selectCoupon">
				<text class="label">优惠券</text>
				<view class="value">
					<text v-if="selectedCoupon">-¥{{couponAmount.toFixed(2)}}</text>
					<text v-else>{{couponText}}</text>
					<u-icon name="arrow-right" color="#999" size="28"></u-icon>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex';
	import {
		delAddressBook,
		getCategoryList,
		getDefaultAddressBook,
		getProducts,
		getShoppingCartLists,
		insertAddressBook,
		setDefaultAddressBook,
		getAllAddressBook,
		getByIdAddressBook,
		payOrder,
	} from "@/request/API.js";
	export default {
		computed: {
			...mapState(['shopDetail', 'subCurrent', 'seatNums']),
			couponText() {
				return this.hasCoupons ? '有可用优惠券' : '暂无可用优惠券';
			},
			actualAmount() {
				let amount = this.totalAmount;
				if (this.selectedCoupon) {
					amount -= this.selectedCoupon.amount;
				}
				return amount.toFixed(2);
			}
		},
		data() {
			return {
				form: {
					mealsTime: '',
					people: 0,
					leave: ''
				},
				couponAmount: 1, // 折扣金
				address: {}, // 默认收货地址
				// orderlist
				orderList: [],
				// orderTotalPrice
				orderPrice: 0,
				// orderNum
				orderNum: 0,
				// u-cell
				valueStyle: {
					fontSize: '26rpx'
				},
				titleStyle: {
					fontWeight: 'bold',
					color: '#333',
					fontSize: '26rpx'
				},
				// popup
				PopupShow: false,
				PopupPage: false,
				// timerSelect
				TimerShow: false,
				TimerParams: {
					year: false,
					month: false,
					day: false,
					hour: true,
					minute: true,
					second: false
				},
				// u-cell
				customStyle: {
					border: "20rpx solid #fff",
					borderRadius: "50rpx",
					padding: '40rpx 0',
					backgroundColor: '#f4f4f5'
				},
				// label
				tags: ['不放辣', '少放辣', '多放辣', '少盐', '不吃蒜', '不吃香菜', '不吃葱', '少油'],
				// input
				inputStyle: {
					backgroundColor: '#f3f4f6',
					borderRadius: "20rpx",
					padding: "30rpx"
				},
				priceDetails: [],
				showPriceDetail: false, // 添加控制折叠面板显示的状态
				defaultTime: this.getDefaultTime(), // 默认时间
				startTime: this.getStartTime(), // 开始时间
				endTime: '22:00', // 结束时间
				selectedCoupon: null, // 选中的优惠券
				totalAmount: 0, // 商品金额
				hasCoupons: false, // 是否有可用优惠券
			}
		},
		onLoad(param) {
			this.getData();
			if (this.subCurrent == 1) {
				this.getDefault(param.addressId);
			}

			// 监听优惠券选择事件
			uni.$on('couponSelected', (coupon) => {
				this.selectedCoupon = coupon;
				// 更新价格明细
				this.updatePriceDetails();
			});
		},
		methods: {
			goToAddress() {
				uni.navigateTo({
					url: "/pages/address/addresslist"
				})
			},
			// 获取默认地址
			async getDefault(id) {
				let data = [];
				if (id) {
					data = await getByIdAddressBook(id);
				} else {
					data = await getDefaultAddressBook();
				}
				this.address = data.data;
			},
			async getData() {
				let that = this;
				const {
					data
				} = await getShoppingCartLists({
					shopId: uni.getStorageSync("shop_id"), // 店铺id
				});
				data.map(item => {
					that.orderPrice += Number(item.amount) * Number(item.number);
					that.orderNum += item.number;
				});
				this.orderList = data;
				let priceDetails = [{
					label: '商品总价',
					value: this.orderPrice
				}];

				if (this.subCurrent != 0) {
					priceDetails.push({
						label: '配送费',
						value: this.shopDetail.deliveryFee
					})
					if (this.shopDetail.packingFee > 0) {
						priceDetails.push({
							label: '打包费',
							value: this.shopDetail.packingFee
						})
					}
				}
				this.priceDetails = priceDetails;
				this.totalAmount = this.orderPrice;
			},
			PopupModal(param) {
				if (param) {
					this.PopupPage = true;
				} else {
					this.PopupPage = false;
				}
				this.PopupShow = true;
			},
			// leave
			SelectTags(param) {
				if (this.form.leave === '') {
					this.form.leave = param;
					return;
				}
				this.form.leave = this.form.leave + '，' + param;
			},
			// NumberDiners
			SelectPeople(param) {
				// #ifdef H5
				this.form.people = param;
				// #endif
				// #ifdef MP-WEIXIN
				this.form.people = param + 1;
				// #endif
				this.PopupShow = false;
				if (this.subCurrent == 0) {
					let priceDetails = this.priceDetails;
					if (this.shopDetail.tablewareFee > 0) {
						let serviceFeeIndex = priceDetails.findIndex(item => item.label === '餐具费');
						if (serviceFeeIndex !== -1) {
							priceDetails[serviceFeeIndex].value = this.form.people * this.shopDetail.tablewareFee;
						} else {
							priceDetails.push({
								label: '餐具费',
								value: this.form.people * this.shopDetail.tablewareFee
							});
						}

					}
					if (this.shopDetail.seatFee > 0) {
						let serviceFeeIndex = priceDetails.findIndex(item => item.label === '餐位费');
						if (serviceFeeIndex !== -1) {
							priceDetails[serviceFeeIndex].value = this.form.people * this.shopDetail.seatFee;
						} else {
							priceDetails.push({
								label: '餐位费',
								value: this.form.people * this.shopDetail.seatFee
							});
						}
					}
					this.priceDetails = priceDetails;
				}
			},
			// PickMealsTimer
			mealsPicker(param) {
				const selectedHour = parseInt(param.hour);
				const selectedMinute = parseInt(param.minute);
				const now = new Date();
				const currentHour = now.getHours();
				const currentMinute = now.getMinutes();
				let select = this.shopDetail.businessHours.split("-\\s*");
				// 检查是否在营业时间范围内
				if (selectedHour < select[0] || selectedHour >= select[1]) {
					this.$u.toast(`配送时间需在${this.shopDetail.businessHours}之间`);
					return;
				}

				// 检查是否选择了当前时间之前的时间
				if (selectedHour < currentHour || (selectedHour === currentHour && selectedMinute < currentMinute)) {
					this.$u.toast('请选择当前时间之后的时间');
					return;
				}

				// 格式化显示时间
				this.form.mealsTime = `${param.hour}:${param.minute}`;
			},
			// confirmPay
			async confirmPay() {
				if (this.orderPrice <= 0) {
					return; // 金额为0时不执行支付
				}
				if (!this.form.people) {
					this.$u.toast('请选择用餐人数')
					return;
				} else {
					// 堂食
					if (this.subCurrent == 0) {
						await payOrder({
							vouchers: this.selectedCoupon.id, // 优惠券编号
							seatNums: Number(this.seatNums), // 桌号
							shopId: uni.getStorageSync("shop_id"), // 店铺id
							seatStatus: this.subCurrent, // 0 堂食 1 外卖
							remark: this.form.leave, // 备注
							tablewareNumber: this.form.people, // 餐具数量
						});
					}
					// 外卖
					if (this.subCurrent == 1) {
						if (!this.form.mealsTime) {
							this.$u.toast('请选择配送时间')
							return;
						} else {
							await payOrder({
								vouchers: this.selectedCoupon.id, // 优惠券编号
								addressBookId: this.address.id, // 地址id
								shopId: uni.getStorageSync("shop_id"), // 店铺id
								seatStatus: this.subCurrent, // 0 堂食 1 外卖
								remark: this.form.leave, // 备注
								tablewareNumber: this.form.people, // 餐具数量
							});
						}
					}
				}
				/* uni.redirectTo({
					url: '/subPack/index/indexPaysuccess'
				}) */
			},
			togglePriceDetail() {
				this.showPriceDetail = !this.showPriceDetail;
			},
			// 修改获取开始时间的方法
			getStartTime() {
				const now = new Date();
				const hours = now.getHours();
				const minutes = now.getMinutes();

				// 如果当前时间在10:00之前
				if (hours < 10) {
					return '10:00';
				}
				// 如果当前时间在22:00之后
				if (hours >= 22) {
					return false;
				}

				// 返回当前时间作为最早可选时间
				return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}`;
			},

			// 修改获取默认时间的方法
			getDefaultTime() {
				const now = new Date();
				const hours = now.getHours();
				const minutes = now.getMinutes();

				// 如果当前时间在10:00之前
				if (hours < 10) {
					return '10:00';
				}
				// 如果当前时间在22:00之后
				if (hours >= 22) {
					return '10:00'; // 显示第二天的开始时间
				}

				// 返回当前时间
				return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}`;
			},
			// 选择优惠券
			selectCoupon() {
				uni.navigateTo({
					url: `/subPack/coupon/couponSelect?amount=${this.totalAmount}&selectedId=${this.selectedCoupon?.id || ''}`
				});
			},
			// 更新价格明细
			updatePriceDetails() {
				let priceDetails = [{
					label: '商品总价',
					value: this.orderPrice
				}];

				// 添加配送费和打包费（外卖时）
				if (this.subCurrent != 0) {
					priceDetails.push({
						label: '配送费',
						value: this.shopDetail.deliveryFee
					});
					if (this.shopDetail.packingFee > 0) {
						priceDetails.push({
							label: '打包费',
							value: this.shopDetail.packingFee
						});
					}
				}

				// 添加餐具费和餐位费（堂食时）
				if (this.subCurrent == 0 && this.form.people > 0) {
					if (this.shopDetail.tablewareFee > 0) {
						priceDetails.push({
							label: '餐具费',
							value: this.form.people * this.shopDetail.tablewareFee
						});
					}
					if (this.shopDetail.seatFee > 0) {
						priceDetails.push({
							label: '餐位费',
							value: this.form.people * this.shopDetail.seatFee
						});
					}
				}

				// 添加优惠券折扣
				if (this.selectedCoupon) {
					let coupon = this.selectedCoupon.couponVO;
					if (coupon.type === "DISCOUNT") {
						// 折扣券
						let discountAmount = -(this.orderPrice * (1 - coupon.value));
						priceDetails.push({
							label: '折扣券',
							value: discountAmount,
							isDiscount: true
						});
						this.couponAmount = discountAmount;
					} else {
						// 满减券
						priceDetails.push({
							label: '优惠券',
							value: -coupon.value,
							isDiscount: true
						});
						this.couponAmount = coupon.value
					}
				}

				this.priceDetails = priceDetails;
			},
		},
		watch: {
			// 监听价格明细变化
			priceDetails: {
				handler(newVal) {
					let price = 0;
					newVal.forEach(item => {
						// 直接使用 value，因为折扣已经计算为负数
						price += item.value;
					});
					this.orderPrice = price;
					this.totalAmount = price;
				},
				deep: true
			},
			// 监听优惠券选择变化
			/* selectedCoupon: {
				handler(newVal) {
					this.updatePriceDetails();
				},
				deep: true
			} */
		},
		onUnload() {
			uni.$off('couponSelected');
		}
	}
</script>

<style lang="scss">
	.wrap {
		.address {
			padding: 30rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;
		}

		.u-cell-box {
			border-radius: 30rpx;
			margin: 30rpx 0;
		}

		.item-menu-image {
			width: 100rpx;
			height: 100rpx;
			border-radius: 20rpx;
		}

		.item-menu-name {
			display: flex;
			flex-direction: column;
			margin-left: 20rpx;
			width: 100%;
		}

		.u-bottom {
			position: fixed;
			bottom: 0;
			width: 100%;
			left: 0;
			right: 0;
			display: flex;
			z-index: 99;

			&__wrap,
			&__place {
				display: flex;
				color: #fff;
			}

			&__wrap {
				width: 70%;
				padding: 30rpx 0 30rpx 30rpx;
				align-items: flex-start;
				color: #303133;
				border-top: 1px solid #f3f4f6;
				background-color: white;
				position: relative;
			}

			&__nums {
				border-left: 1px solid #606266;
				font-size: 24rpx;
				margin-left: 20rpx;
				padding-left: 20rpx;
				font-weight: bold;

				.check-detail {
					color: #f37b1d;
					font-size: 24rpx;
					margin-top: 10rpx;
					display: flex;
					align-items: center;

					text {
						margin-right: 4rpx;
					}
				}
			}

			&__place {
				background-color: #EE2F37;
				width: 30%;
				text-align: center;
				flex-direction: column;
				justify-content: center;
				font-size: 32rpx;
				font-weight: bold;
				transition: background-color 0.3s;

				&--disabled {
					background-color: #c8c9cc !important;
					pointer-events: none;
					cursor: not-allowed;
				}
			}

			// 添加遮罩层样式
			.mask {
				position: fixed;
				top: 0;
				left: 0;
				right: 0;
				bottom: 0;
				background-color: transparent;
				z-index: 98;
			}

			.price-detail-panel {
				position: absolute;
				top: 0;
				left: 0;
				width: 100%;
				background-color: #fff;
				padding: 0 30rpx;
				transform: translateY(-100%);
				max-height: 0;
				overflow: hidden;
				transition: all 0.3s ease;
				box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
				border-radius: 20rpx 20rpx 0 0;
				z-index: 100; // 确保面板在最上层

				&.panel-show {
					padding: 20rpx 30rpx;
					max-height: 300rpx;
				}

				.price-list {
					opacity: 0;
					transition: opacity 0.3s ease;

					.price-item {
						display: flex;
						justify-content: space-between;
						margin-bottom: 20rpx;
						font-size: 28rpx;
						color: #333;

						&:last-child {
							margin-bottom: 0;
						}

						// 优惠金额显示为红色
						text:last-child {
							&.discount {
								color: #EE2F37;
							}
						}
					}
				}

				&.panel-show .price-list {
					opacity: 1;
				}
			}
		}

		.list-box {
			padding: 20rpx 30rpx;
			margin: 0 30rpx 20rpx 30rpx;
			margin-bottom: 20rpx;
			border-radius: 14rpx;
			box-shadow: 2px 0px 8px 0px rgba(243, 244, 246, 0.95);
		}

		.goods-count {
			position: fixed;
			bottom: 0;
			width: 100%;
			left: 0;
			right: 0;
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 20rpx;
			background-color: #fff;
			border-top: 1px solid #f3f4f6;

			.check-detail {
				color: #666;
				font-size: 24rpx;
				margin-top: 10rpx;
				text-decoration: underline;
			}
		}

		.discount-section {
			background: #fff;

			.section-item {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 0rpx 30rpx;

				.label {
					font-size: 28rpx;
					color: #333;
				}

				.value {
					display: flex;
					align-items: center;
					font-size: 28rpx;
					color: #666;

					text {
						margin-right: 8rpx;

						&.discount {
							color: #EE2F37;
						}
					}
				}
			}
		}

		.price-info {
			background: #fff;
			padding: 30rpx;
			margin-top: 20rpx;

			.price-item {
				display: flex;
				justify-content: space-between;
				margin-bottom: 20rpx;
				font-size: 28rpx;
				color: #666;

				.discount {
					color: #EE2F37;
				}
			}

			.price-total {
				display: flex;
				justify-content: space-between;
				padding-top: 20rpx;
				border-top: 1rpx solid #f5f5f5;
				font-size: 32rpx;
				font-weight: bold;

				.amount {
					color: #EE2F37;
				}
			}
		}
	}
</style>